import { createRouter, createWebHistory } from 'vue-router'
import Login from '@/components/auth/Login.vue'
import Home from '@/components/Home.vue'
import Register from '@/components/auth/Register.vue'
import Ranking from '@/components/home/Ranking.vue'
import UserProfile from '@/components/profile/UserProfile.vue'
import UserOrders from '@/components/orders/UserOrders.vue' // 导入订单页面

const routes = [
    {
        path: '/login',
        name: 'Login',
        component: Login,
    },
    {
        path: '/register',
        name: 'Register',
        component: Register,
    },
    {
        path: '/',
        name: 'Home',
        component: Home,
        meta: { requiresAuth: true },
    },
    {
        path: '/ranking',
        name: 'Ranking',
        component: Ranking,
        meta: { requiresAuth: true },
    },
    {
        path: '/profile',
        name: 'Profile',
        component: UserProfile,
        meta: { requiresAuth: true },
    },
    // 添加订单路由
    {
        path: '/orders',
        name: 'Orders',
        component: UserOrders,
        meta: { requiresAuth: true },
    },
]

const router = createRouter({
    history: createWebHistory(),
    routes,
})

router.beforeEach((to, from, next) => {
    const token = localStorage.getItem('auth_token')
    if (to.meta.requiresAuth && !token) {
        next('/login')
    } else if ((to.path === '/login' || to.path === '/register') && token) {
        next('/')
    } else {
        next()
    }
})

export default router